<?php
/**
 * User: Mykola B.
 * Date: 3/1/13
 * Time: 6:43 PM
 */
namespace controllers {

    class UserController
    {
        // cookie name / user profile parameter key
        private static $identityKey = 'session_user_id';

        public function loginGet($f3) {
            if ($f3->get('is_authenticated')) {
                $f3->reroute('/');
            }
            $template = new \Template();
            echo $template->render('login.html');
        }

        public function loginPost($f3) {
            $user = new \models\UserModel();
            $user->getByName('admin');
            $inputName = $f3->get('POST.username');
            $inputPassword = $f3->get('POST.password');
            if (!empty($inputName) && !empty($inputPassword)) {

                if ($this->equalPasswords($inputPassword, $user->password, $f3)) {
                    $this->login($user, $f3);
                    $f3->reroute($f3->get('GET.url', '/'));
                }

            } else {
                $f3->reroute('/login');
            }
        }

        public function logout($f3) {
            if ($f3->get('is_authenticated')) {
                $session = $f3->get('SESSION');
                unset($session['user']);
                $f3->set('SESSION', $session);
            }
            $f3->reroute('/');
        }

        /**
         * Compare entered and database passwords.
         * @param $inputPass
         * @param $DBpass
         * @return bool
         */
        private function equalPasswords($inputPass, $DBpass, $f3) {
            $salt = $f3->get('SETTINGS')->salt;
            return md5($inputPass + $salt) === $DBpass;
        }

        public function isAuthenticated($f3) {
            $cookies = $f3->get('COOKIE');
            $session = $f3->get('SESSION');
            // no user in session
            if (!isset($session['user'])) return false;
            // no cookie
            if (!isset($cookies[self::$identityKey])) return false;

            list($token, $hmac) = explode(':', $cookies[self::$identityKey], 2);
            if ($hmac != hash_hmac('md5', $token, $f3->get('SETTINGS')->salt)) {
                return false; // cookie has been tampered with
            }
            return true;
        }

        private function login(\models\UserModel $user, $f3) {
            $randomToken = hash('sha256',uniqid(mt_rand(), true).uniqid(mt_rand(), true));

            $userProfile = new \models\UserProfileModel();
            $userProfile->fillObject($user, self::$identityKey, $randomToken);
            $userProfile->save();

            $randomToken .= ':'.hash_hmac('md5', $randomToken, $f3->get('SETTINGS')->salt);
            setcookie(self::$identityKey, $randomToken, time() + 60 * 30); // expire in half an hour
            $session = $f3->get('SESSION');
            $session['user'] = $user;
            $f3->set('SESSION', $session);
        }
    }

}
